"""
用户相关序列化器
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from pecco_site.models import UserProfile, Cart, CartItem


class UserProfileSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""
    class Meta:
        model = UserProfile
        fields = [
            'phone', 'avatar', 'company',
            'address_line1', 'address_line2',
            'city', 'state', 'postal_code', 'country',
            'total_orders', 'total_spent', 'preferred_language',
            'newsletter_subscribed', 'created_at', 'updated_at'
        ]
        read_only_fields = ['total_orders', 'total_spent', 'created_at', 'updated_at']


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    profile = UserProfileSerializer(read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'profile', 'date_joined']
        read_only_fields = ['id', 'date_joined']


class UserRegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    password_confirm = serializers.CharField(write_only=True)
    newsletter_subscribed = serializers.BooleanField(default=False, required=False)
    company = serializers.CharField(required=False, allow_blank=True, max_length=120)
    
    # 地址字段
    phone = serializers.CharField(required=True, max_length=20)
    country = serializers.CharField(required=True, max_length=100)
    state = serializers.CharField(required=True, max_length=100)
    city = serializers.CharField(required=True, max_length=100)
    address_line1 = serializers.CharField(required=True, max_length=255)
    address_line2 = serializers.CharField(required=False, allow_blank=True, max_length=255)
    
    def validate_phone(self, value):
        """验证手机号只能包含数字、空格、加号和连字符"""
        import re
        # 移除空格、加号和连字符后，检查是否只包含数字
        cleaned_phone = re.sub(r'[\s\+\-]', '', value)
        if not cleaned_phone.isdigit():
            raise serializers.ValidationError("Phone number must contain only digits, spaces, plus sign, and hyphens.")
        if len(cleaned_phone) < 6:
            raise serializers.ValidationError("Phone number must be at least 6 digits.")
        return value
    
    # 隐私条款同意
    privacy_agreed = serializers.BooleanField(required=True)
    
    class Meta:
        model = User
        fields = [
            'username', 'email', 'password', 'password_confirm', 
            'first_name', 'last_name', 'newsletter_subscribed', 'company',
            'phone', 'country', 'state', 'city', 'address_line1', 'address_line2',
            'privacy_agreed'
        ]
    
    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("This username is already taken.")
        return value
    
    def validate_email(self, value):
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("This email is already registered.")
        return value
    
    def validate_privacy_agreed(self, value):
        if not value:
            raise serializers.ValidationError("You must agree to the privacy policy to register.")
        return value
    
    def validate(self, data):
        if data['password'] != data['password_confirm']:
            raise serializers.ValidationError({"password_confirm": "Passwords do not match."})
        return data
    
    def create(self, validated_data):
        from pecco_site.models import UserAddress
        
        # 提取非User模型字段
        validated_data.pop('password_confirm')
        newsletter_subscribed = validated_data.pop('newsletter_subscribed', False)
        company = validated_data.pop('company', '')
        phone = validated_data.pop('phone')
        country = validated_data.pop('country')
        state = validated_data.pop('state')
        city = validated_data.pop('city')
        address_line1 = validated_data.pop('address_line1')
        address_line2 = validated_data.pop('address_line2', '')
        validated_data.pop('privacy_agreed')  # 只是验证，不存储
        
        # 创建用户
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password'],
            first_name=validated_data.get('first_name', ''),
            last_name=validated_data.get('last_name', '')
        )
        
        # 更新用户资料（signal已自动创建）
        profile = user.profile
        profile.company = company
        profile.phone = phone
        profile.newsletter_subscribed = newsletter_subscribed
        profile.save()
        
        # 创建默认地址
        UserAddress.objects.create(
            user=user,
            first_name=user.first_name,
            last_name=user.last_name,
            company=company,
            phone=phone,
            country=country,
            state=state,
            city=city,
            address_line1=address_line1,
            address_line2=address_line2,
            postal_code='',  # 邮编设为空
            is_default=True  # 设置为默认地址
        )
        
        return user


class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)


class UserUpdateSerializer(serializers.ModelSerializer):
    """用户更新序列化器"""
    profile = UserProfileSerializer(required=False)
    
    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'profile']
    
    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile', None)
        
        # 更新User字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新Profile字段
        if profile_data:
            profile = instance.profile
            for attr, value in profile_data.items():
                setattr(profile, attr, value)
            profile.save()
        
        return instance

